namespace SimpleWebServices.Web.UI.Html.Validation
{
    using System;
    using System.Xml;
    using SimpleWebServices.Data;
    using SimpleWebServices.Web.UI.Html.Elements;

    public sealed class StandardCheckBoxValidator : Validator
    {
        public StandardCheckBoxValidator()
            : this(null, null)
        {
        }

        public StandardCheckBoxValidator(IInnerElements display, bool? isChecked)
            : base(display)
        {
            this.IsChecked = isChecked;
        }

        public bool? IsChecked
        {
            get;
            set;
        }

        public override void Configure(IElement element, DataCollection data)
        {
            base.Configure(element, data);

            if (null != data)
            {
                foreach (var datum in data)
                {
                    if ("IsChecked".Equals(datum.Key, StringComparison.OrdinalIgnoreCase))
                    {
                        this.IsChecked = XmlConvert.ToBoolean(datum.Value);
                    }
                }
            }
        }

        public override bool Validate(IElement element)
        {
            if (null == element)
            {
                throw new ArgumentNullException("element");
            }

            return this.Validate(element as CheckBoxInput);
        }

        private bool Validate(CheckBoxInput control)
        {
            if (null == control)
            {
                throw new ArgumentOutOfRangeException("control");
            }

            this.Errors.Clear();

            if (this.IsChecked.HasValue)
            {
                if (this.IsChecked != control.Checked)
                {
                    this.Errors.Add(new Error(this.ErrorText));
                }
            }

            return 0 == this.Errors.Count;
        }
    }
}